package com.yy.studyspringboot.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
    /**  CycliBarrier---同步器
        同步等待  效果，等所有玩家准备好了才开始游戏
     * */
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
            @Override
            public void run() {
                System.out.println("game start");
            }
        });

        new Player(cyclicBarrier,"A").start();
        new Player(cyclicBarrier,"B").start();
        new Player(cyclicBarrier,"B").start();

        //效果，等所有玩家准备好了才开始游戏
    }
}

class Player extends Thread{
    private CyclicBarrier cyclicBarrier;
    public Player(CyclicBarrier cyclicBarrier,String name){
        setName(name);
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        System.out.println(getName() + "is waiting other players ....");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    }
}